package com.zzz.hook;

import android.content.Context;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class HookUtil {
    private Class<?> proxyActivity;

    private Context mContext;

    public HookUtil(Class<?> proxyActivity,Context context){
        this.proxyActivity=proxyActivity;
        this.mContext=context;
    }

    public void hookactivity(){
        try {
            Class<?> activityManagerNativeClass=Class.forName("android.app.ActivityManagerNative");
            Field defaultField=activityManagerNativeClass.getDeclaredField("gDefault");
            defaultField.setAccessible(true);
            Object defaultValue=defaultField.get(null);
            Class<?> singletonClass=Class.forName("android.util.Singleton");
            Field mInstance=singletonClass.getDeclaredField("mInstance");
            mInstance.setAccessible(true);
            Object iActivityManagerObject = mInstance.get(defaultValue);

            Class<?> iActivityManagerIntercept = Class.forName("android.app.IActivityManager");
            AmsInvocationHandler handler = new AmsInvocationHandler(iActivityManagerObject);
            Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{iActivityManagerIntercept}, handler);

            //现在替换掉这个对象
            mInstance.set(defaultValue, proxy);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
